<template>
  <md-nav-bar
    title=""
    color="white"
    :bgInfo="{ url: data.detail?.coverUrl || 'https://cdn.xmxiaomai.com/isong_static/evaluation/indexTopBg.png' }" />
  <view class="music-detail-container">
    <!-- 歌曲信息卡片 -->
    <view class="music-info-card">
      <view class="music-title-row">
        <view class="music-title">{{ data.detail?.name }}</view>
        <view class="music-like">
          <image class="like-icon" src="https://cdn.xmxiaomai.com/isong_static/music/icon-%E8%B5%9E.png" />
          <text class="ike-num">{{ data.detail?.likesNum }}</text>
        </view>
        <view class="music-avatar-wrap" @click="handleMemberDetail">
          <image class="music-avatar" :src="data.detail?.memberUser?.avatar" />
          <view class="music-author-badge">{{ data.detail?.memberUser?.nickname }}</view>
        </view>
      </view>
      <view class="music-meta">
        <view>作词：{{ data.detail?.wording }}</view>
        <view>作曲：{{ data.detail?.composer }}</view>
      </view>
      <view class="music-meta">
        <view>演唱：{{ data.detail?.singer }}</view>
      </view>
      <view class="music-btns">
        <view class="music-btn" @click="onBg">查看创作背景</view>
        <view class="music-btn" @click="onPlay">查看歌词</view>
      </view>
      <image class="play-icon" @click="onPlay" src="https://cdn.xmxiaomai.com/isong_static/music/Group%2014.png" />
    </view>

    <!-- 评论Tab -->
    <view class="comment-tabs">
      <view :class="['tab', commentTab === 0 ? 'active' : '']" @click="commentTab = 0">精彩评论</view>
      <view :class="['tab', commentTab === 1 ? 'active' : '']" @click="commentTab = 1">AI评价</view>
      <view class="comment-actions">
        <!-- 点赞 -->
        <md-handle-like :musicId="data.id" :status="!!data.detail?.likeStatus" />
        <!-- 分享 -->
        <md-share-btn :title="data.share.title" :image-url="data.share.imageUrl" :path="data.share.path" />
      </view>
    </view>

    <!-- 评论列表 -->
    <view class="comment-list" v-if="commentTab === 0">
      <md-page-list ref="pageRef" :api="api.Music.comment" :params="{ musicId: data.id }" @change="pageChange">
        <view v-for="(item, idx) in data.comments" :key="idx" class="comment-item">
          <image class="comment-avatar" :src="item.avatar" />
          <view class="comment-main">
            <view class="comment-user">{{ item.nickname }}</view>
            <view class="comment-content">{{ item.content }}</view>
            <tamplete v-if="item.childList.list.length > 0">
              <view
                class="comment-reply"
                v-for="child in item.childList.list"
                :key="child.id"
                @click="() => handleReplyComment(child, Number(item?.id))">
                <text class="user-label">{{ child.nickname }}</text>
                <text class="reply-label">回复</text>
                <text v-if="child.replyName" class="reply-user">{{ child.replyName }}：</text>
                <text class="reply-content">{{ child.content }}</text>
              </view>
              <uni-load-more
                v-if="item.childList?.total > 10 && !((data.pagesInfo?.topId || 1) > item.childList?.total / 10)"
                :status="
                  data.loading
                    ? 'loading'
                    : (data.pagesInfo?.topId || 1) > item.childList?.total / 10
                    ? 'noMore'
                    : 'more'
                "
                :content-text="data.contentText"
                @clickLoadMore="
                  () =>
                    handleMore({
                      topId: Number(item?.id),
                      total: item.childList.total,
                    })
                " />
            </tamplete>
            <view class="comment-date">
              <text>{{ item.createTime }}</text>
              <!-- 回复评论 -->
              <image
                class="comment-icon"
                src="https://cdn.xmxiaomai.com/isong_static/music/%E5%8F%91%E8%A8%80.png"
                @click="() => handleReplyComment(item, Number(item?.id))" />
            </view>
          </view>
        </view>
      </md-page-list>
    </view>
    <!-- 底部输入 -->
    <view class="comment-input-bar-wrap" v-if="commentTab === 0">
      <view v-if="data.replyUser" class="reply-user">回复 {{ data.replyUser }}</view>
      <view class="comment-input-bar">
        <image class="input-icon" src="https://cdn.xmxiaomai.com/isong_static/music/%E8%AF%84%E8%AE%BA.png" />
        <input
          v-model="data.content"
          class="comment-input"
          placeholder="发表评论"
          confirm-type="send"
          @confirm="() => handleConfirmComment()"
          @blur="onCommentBlur" />
      </view>
    </view>
    <!-- AI评价内容 -->
    <view v-if="commentTab === 1" class="ai-eval-wrap">
      <view class="ai-score-card" :style="{ margin: data.detail?.evaluationRecords?.aiScore ? '160rpx 45rpx 0' : '50rpx 45rpx 0' }">
				<view class="ai-score-wrap" v-if="data.detail?.evaluationRecords?.aiScore">
					<view class="ai-score-bg">
						<view class="ai-score-badge">
              {{ data.detail?.evaluationRecords?.aiScore || '' }}
							<!-- <view class="ai-score-num"></view> -->
						</view>
					</view>
					<view class="ai-score-title">AI综合评分</view>
				</view>
        <view class="ai-hr"></view>
        <!-- 评价内容 -->
        <view class="ai-section" >
          <mp-html
              :content="data.detail.evaluationRecords?.songEvaluation"
              container-style="display:flex;font-size: 30rpx; text-align: justify;"
              :tag-style="{
              p: 'padding:20rpx',
              ul: 'padding:20rpx 0 20rpx 40rpx'
            }"
          ></mp-html>
        </view>
        <view class="ai-section-tip">测评结果为AI大模型算法自动生成，仅供参考</view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import {onLoad, onShareAppMessage, onShareTimeline} from '@dcloudio/uni-app';
// 接口
import api from '@/api';
import type { Music } from '@/api/data';
import UniPopupDialog from "@/uni_modules/uni-popup/components/uni-popup-dialog/uni-popup-dialog.vue";

const data = reactive({
  id: -1,
  detail: {} as Music.Detail.Data,
  canReset: false,
  comments: [] as Music.Comment.Data['list'],
  content: '', // 添加的评论内容
  replyUser: '', // 回复的用户昵称
  parentId: 0, // 评论的父id, 用于回复评论，首评为0
  topId: null as number | null, // 首评id
  contentText: {
    contentdown: '查看更多',
    contentrefresh: '加载中',
    contentnomore: '没有更多',
  },
  status: 'more',
  pagesInfo: {} as Record<string, any>, // 收集各个子评论列表当前的currentNo
  loading: false,
  userId: '',
  share:{}
});
const pageRef = ref<any>(null);
const popup = ref<any>(null);
const commentTab = ref(0);
const evalTabs = ['歌词评价', '旋律评价', '总结'];
const evalTab = ref(0);

// 跳音乐人详情
const handleMemberDetail = () => {
  uni.navigateTo({
    url: `/pages/sub/index/musicianDetails?id=${data.detail?.memberUser?.id}`,
  });
};

function onBg() {
  uni.setStorageSync('background', data.detail?.background);
  uni.navigateTo({
    url: `/pages/sub/index/musicBackground`,
  });
}

// 跳转播放页面
function onPlay() {
  uni.navigateTo({
    url: `/pages/sub/square/musicPlayer?id=${data.detail?.id}`,
  });
}

/**
 * 评论相关处理
 */
// 评论
const handleConfirmComment = (parentId?: number) => {
  if (!data.content.trim()) {
    uni.showToast({ title: '评论内容不能为空', icon: 'none' });
    return;
  }
  fetchGetComment(parentId);
};

// 子评论分页处理
const handleMore = (params: { total: number; topId: number }) => {
  let currentPageNo = data.pagesInfo?.topId || 1;
  const totalPage = params?.total / 10;
  // 没有分页，则不触发分页
  if (currentPageNo > totalPage) {
    return;
  }
  const nextPageNo = ++currentPageNo;
  data.pagesInfo = { ...data.pagesInfo, topId: nextPageNo };
  fetchGetChildCommentPage({ topId: params?.topId, pageNo: nextPageNo });
};

// 回复
const handleReplyComment = (item: Music.Comment.ListVo, topId: number) => {
  if (item?.id) {
    data.parentId = item.id;
    data.topId = topId;
    data.replyUser = item.nickname; // 回复的用户昵称
  }
};

const onCommentBlur = () => {
  // 重置一下回复id
  data.parentId = 0;
  data.topId = null;
  data.replyUser = '';
  data.content = '';
};

/**
 * 接口相关
 */
// 音乐广场详情
const fetchGetDetail = async (id: number) => {
  try {
    const res = await api.Music.detail({ id });
    if (res?.data) {
      data.detail = res.data;
			// 音乐测评解析
			// if (data.detail.evaluationRecords) {
			// 	data.detail.evaluationRecords.lyricsEvaluation =
			// 		data.detail.evaluationRecords.lyricsEvaluation ?
			// 		JSON.parse(data.detail.evaluationRecords.lyricsEvaluation) : '';
			// 	data.detail.evaluationRecords.songEvaluation =
			// 		data.detail.evaluationRecords.songEvaluation ?
			// 		JSON.parse(data.detail.evaluationRecords.songEvaluation) : '';
			// }
      data.share = {
        title: data.detail?.name,
        path: '/pages/sub/square/musicDetail?id=' + data.id + (data.userId ? ('&parentId=' + data.userId) : ''),
        imageUrl: data.detail?.coverUrl,
      };
    } else {
      uni.showModal({
        title: '提示',
        content: '歌曲已隐藏',
        showCancel: false,
      });
    }
  } catch (error) {}
};

// 创建评论记录
const fetchGetComment = async (parentId?: number) => {
  try {
    await api.Music.createComment({
      parentId: parentId || data.parentId,
      topId: data?.topId ? data.topId : undefined,
      musicId: data.id,
      content: data.content,
    });
    // 重新刷新分页
    pageRef.value?.onRefresh();
    data.pagesInfo = {};
  } catch (error) {
    console.error('获取评论失败', error);
  }
};

// 分页处理
const pageChange = (list: Music.Comment.Data['list']) => {
  data.comments = list;
};

// 获取子评论分页
const fetchGetChildCommentPage = async (params: { pageNo: number; topId: number }) => {
  data.loading = true;
  try {
    const res = await api.Music.childComment({
      musicId: data.id,
      pageSize: 10,
      ...params,
    });
    data.comments.forEach(item => {
      if (item.id === params.topId && Array.isArray(res.data.list)) {
        item.childList.list = item.childList.list.concat(res.data.list);
      }
    });
  } catch (error) {}
  data.loading = false;
};

onShareTimeline(() => {
  return {
    title: data.share.title || 'isong music',
    imageUrl: data.share.imageUrl || 'https://cdn.xmxiaomai.com/isong_static/share.jpg',
    query: 'id='+data.id + (data.userId ? ('&parentId=' + data.userId) : ''),
  };
});

onLoad((options: any) => {
  const scene = options.scene ? decodeURIComponent(options.scene) : ''
  data.id = scene ? scene : options.id;
  data.userId = uni.getStorageSync('auth')?.userId;
  fetchGetDetail(data.id);
});
</script>

<style lang="scss" scoped>
.music-detail-container {
  min-height: 100vh;
  background: #f5f8f7;
  padding-bottom: 120rpx;
}
.music-bg {
  width: 100vw;
  height: 320rpx;
  object-fit: cover;
  display: block;
}
.music-info-card {
  background: #fff;
  border-radius: 48rpx 48rpx 0 0;
  margin-top: -48rpx;
  padding: 40rpx 32rpx 45rpx 32rpx;
  box-shadow: 0 4rpx 24rpx 0 #e0e0e0;
  position: relative;
  z-index: 2;
}
.music-title-row {
  position: relative;
  display: flex;
  align-items: center;
  margin-bottom: 26rpx;
}
.music-title {
  font-size: 36rpx;
  color: #222;
  font-weight: 700;
  margin-right: 12rpx;
}
.music-like {
  font-size: 24rpx;
  color: #1fa37a;
  margin-right: 12rpx;
  display: flex;
  align-items: center;
}
.like-icon {
  font-size: 32rpx;
  margin-right: 2rpx;
  width: 36rpx;
  height: 36rpx;
}
.like-num {
  margin-top: -10rpx;
  margin-left: -10rpx;
}

.music-avatar-wrap {
  position: absolute;
  right: 0rpx;
  top: -95rpx;
  width: 182rpx;
  // height: 122rpx;
  text-align: center;
  .music-avatar {
    width: 122rpx;
    height: 122rpx;
    border-radius: 50%;
    background: #eee;
    margin-right: 8rpx;
    margin-left: auto;
    border: 4rpx solid #fff;
  }
  .music-author-badge {
    background: #1fa37a;
    color: #fff;
    font-size: 24rpx;
    border-radius: 24rpx;
    padding: 0 18rpx;
    height: 40rpx;
    line-height: 40rpx;
    font-weight: 500;
    z-index: 2;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
.music-meta {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  color: #444;
  margin-bottom: 10rpx;
}
.music-meta > view {
  margin-right: 32rpx;
}
.music-btns {
  display: flex;
  align-items: center;
  margin-top: 18rpx;
}
.music-btn {
  background: #fff;
  color: #1fa37a;
  border: 2rpx solid #1fa37a;
  border-radius: 32rpx;
  font-size: 28rpx;
  padding: 0 32rpx;
  height: 56rpx;
  line-height: 56rpx;
  margin-right: 18rpx;
  font-weight: 500;
}
.play-icon {
  width: 90rpx;
  height: 90rpx;
  position: absolute;
  top: 177rpx;
  right: 83rpx;
}
.comment-tabs {
  display: flex;
  align-items: center;
  background: #fff;
  margin: 24rpx 0 0 0;
  padding: 0 24rpx;
  border-bottom: 2rpx solid #f0f0f0;
  position: relative;
}
.tab {
  font-size: 32rpx;
  color: #222;
  font-weight: 500;
  margin-right: 48rpx;
  padding: 32rpx 0 18rpx 0;
  position: relative;
  opacity: 0.7;
}
.tab.active {
  color: #1fa37a;
  opacity: 1;
}
.tab.active::after {
  content: '';
  display: block;
  width: 48rpx;
  height: 6rpx;
  background: #1fa37a;
  border-radius: 3rpx;
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
}
.comment-actions {
  position: absolute;
  right: 24rpx;
  top: 32rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}
.comment-list {
  background: #fff;
  border-radius: 0;
  margin: 0;
  padding: 0 0 24rpx 0;
}
.comment-item {
  display: flex;
  align-items: flex-start;
  padding: 24rpx 24rpx 0 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}
.comment-avatar {
  width: 74rpx;
  height: 74rpx;
  border-radius: 50%;
  // background: #eee;
  margin-right: 18rpx;
  flex-shrink: 0;
}
.comment-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.comment-user {
  font-size: 28rpx;
  color: #8b8886;
  font-weight: 400;
  margin-bottom: 10rpx;
}
.comment-reply {
  background: #f5f8f7;
  border-radius: 12rpx;
  padding: 8rpx 16rpx;
  font-size: 26rpx;
  color: #1fa37a;
  margin-bottom: 4rpx;
  display: flex;
  align-items: center;
}
.user-label {
  color: #8b8886;
  font-weight: 400;
  margin-right: 8rpx;
}
.reply-label {
  color: #1fa37a;
  margin-right: 4rpx;
}
.reply-user {
  color: #1fa37a;
  margin-right: 4rpx;
}
.reply-content {
  color: #444;
}
.comment-content {
  font-size: 28rpx;
  color: #222;
  margin-bottom: 16rpx;
  word-break: break-all;
}
.comment-date {
  font-size: 24rpx;
  color: #bbb;
  height: 33rpx;
  line-height: 33rpx;
  margin-bottom: 16rpx;
  justify-content: space-between;
  display: flex;
  .comment-icon {
    width: 32rpx;
    height: 32rpx;
    margin-right: 21rpx;
    vertical-align: middle;
  }
}

.comment-input-bar-wrap {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #ffffff;
  padding: 24rpx 24rpx 32rpx 24rpx;
  z-index: 10;
  .reply-user {
    color: #666;
  }
}
.comment-input-bar {
  display: flex;
  align-items: center;
}
.input-icon {
  font-size: 32rpx;
  color: #1fa37a;
  margin-right: 12rpx;
  width: 40rpx;
  height: 40rpx;
  position: absolute;
  left: 60rpx;
}
.comment-input {
  flex: 1;
  height: 64rpx;
  border: none;
  border-radius: 44rpx;
  font-size: 28rpx;
  color: #222;
  background: #f4f4f4;
  padding: 0 92rpx;
}
.ai-eval-wrap {
  margin: 0 0 24rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.ai-score-card {
  background: #fff8ed;
  border-radius: 32rpx;
  margin: 160rpx 45rpx 0;
  padding: 32rpx 24rpx 24rpx;
  box-shadow: 0 4rpx 24rpx 0 #ffe7b2;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.ai-score-wrap {
	text-align: center;
}
.ai-score-bg {
  width: 318.43rpx;
  height: 170.95rpx;
  background: url('https://cdn.xmxiaomai.com/isong_static/music/Group%2015%403x.png') no-repeat center center;
  background-size: cover;
  margin-top: -120rpx;
  margin-bottom: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.ai-score-badge {
  width: 120rpx;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  font-size: 38rpx;
  color: #b88a2a;
  font-weight: 700;
  text-align: center;
}
.ai-score-num {
  font-size: 48rpx;
  color: #b88a2a;
  font-weight: 700;
}
.ai-score-title {
  font-size: 30rpx;
  color: #1fa37a;
  font-weight: 600;
  margin-bottom: 8rpx;
}
.ai-score-desc {
  font-size: 26rpx;
  color: #444;
  margin-bottom: 18rpx;
  text-align: center;
}
.ai-hr {
  width: 600rpx;
  height: 1rpx;
  border: 2rpx solid #85c5b6;
  margin: 24rpx 0;
}
.ai-eval-tabs {
  width: 600rpx;
  height: 68rpx;
  background: #ffffff;
  box-shadow: 0rpx 0rpx 8rpx 4rpx #f5deb9;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  margin-bottom: 18rpx;
}
.eval-tab {
  font-size: 28rpx;
  color: #008466;
  background: #fff;
  border-radius: 28rpx;
  padding: 8rpx 24rpx;
  // border: 2rpx solid #1fa37a;
  opacity: 0.7;
}
.eval-tab.active {
  background: #008466;
  color: #fff;
  opacity: 1;
}
.ai-section {
  width: 100%;
}
.ai-section-title {
  font-size: 28rpx;
  color: #008466;
  font-weight: 600;
  margin: 18rpx 0 21rpx 0;
  align-self: flex-start;
  .ai-icon {
    width: 30rpx;
    height: 30rpx;
    vertical-align: middle;
    margin-right: 12rpx;
  }
}
.ai-section-list {
  width: 100%;
  margin-bottom: 8rpx;
}
.ai-section-item {
  font-size: 26rpx;
  color: #444;
  margin-bottom: 6rpx;
  display: flex;
  align-items: flex-start;
}
.ai-section-num {
  color: #1fa37a;
  margin-right: 6rpx;
}
.ai-section-summary {
  font-size: 26rpx;
  color: #444;
  margin-bottom: 8rpx;
  text-align: left;
  width: 100%;
}
.ai-section-tip {
  font-size: 22rpx;
  color: #bbb;
  margin-top: 18rpx;
  align-self: flex-start;
}
.dialog-background {
  color: black;
  height: 480rpx;
  overflow: scroll;
}
</style>
